<?php

namespace App\Http\Controllers;

use App\Models\UserLoginModel;
use App\service\AddFoot;
use App\service\AuthLogin;
use App\service\JwtService;
use App\service\ReturnService;
use App\service\SendMessage;
use App\service\TokenBucket;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class LoginController extends Controller
{
    //获取浏览数据记录
    public function foot(Request $request)
    {

        AddFoot::addFoot(1, 5);
        $token = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOi8vd3d3LmdvdXAuY29tIiwiYXVkIjoiaHR0cDovL3d3dy5nb3VwLmNvbSIsImRhdGEiOjF9.M4wycwTiMEmgMxCbdh5aUyA5ELCyL0Zpugv8wbiSs9M';
        $user = JwtService::decodeToken($token);
        $id = $user->data;
        $len = Redis::lLen('_user_foot' . $id);
        if ($len == 0) {
            return ReturnService::failedReturn('200', '您当前没有历史痕迹哦');
        }
        $data = Redis::lrange('_user_foot' . $id, 0, $len);
        $new = DB::table('gr_goods')->whereIn('goods_id', $data)->get()->toArray();
        //浏览记录获取成功
        return ReturnService::successReturn(200, '历史记录获取成功', $new);
    }

    //echarts
    public function echarts()
    {

        $a = new TokenBucket();
        var_dump($a->getApi());
        die();
        $data = DB::table('gr_type')->get();
        dd($data);
        $data = [];
        //$data[4]=DB::table('students')->pluck('number');
        $data[0] = 1;
        $data[1] = 2;
        $data[2] = 3;
        $data[3] = 4;
        $data[4] = 5;
        return view('echarts', compact('data'));
    }

    //授权登录
    public function authLogin(Request $request)
    {
        $data = $request->post();
        $code = $data['code'];
        //换取openid和sessionkey
        $res = AuthLogin::userLogin($code);
        $sessionKey = $res['session_key'];
        $openid = $res['openid'];
        $head = $data['code'];
        $nickname = $data['nickName'];

        $user = UserLoginModel::where('openid', $openid)->first();
        //如果为空则插入数据
        if (empty($user)) {
            //判断是否授权成功
            $auth_id = UserLoginModel::insertGetId([
                'session_key' => $sessionKey,
                'openid' => $openid,
                'username' => $nickname,
                'head_portrait' => $head]);
            if ($auth_id) {
                $token = JwtService::getToken($auth_id);
                return ReturnService::successReturn(200, '登陆成功', $token);
            }
            return ReturnService::failedReturn(400, '登陆失败');
        }
        //如果不为空则更新sessionKey

        $user = UserLoginModel::where('openid', $openid)->first();
        $user_id = $user['id'];
        //更新数据
        $auth_res = UserLoginModel::where('id', $user_id)->update(['session_key' => $sessionKey]);
        if ($auth_res) {
            $token = JwtService::getToken($user_id);
            //判断
            return ReturnService::successReturn(200, '登陆成功', $token);
        } else {
            return ReturnService::failedReturn(400, '登陆失败');
        }
    }

    //发送短信
    public function sendCaptcha(Request $request)
    {
        $tel = $request->get('tel');
        $content = mt_rand(1000, 9999);
        $oldTime = Redis::get('_send_time' . $tel);
        if (time() - $oldTime < 60) {
            return ReturnService::failedReturn(400, '短信发送太频繁');
        }
        if (!empty($tel)) {
            //发送短信
//            $res = SendMessage::Send($tel, $content);
            $res = 0;
            if ($res == 0) {
                //发送成功记录短信和发送时间
                Redis::set('_send_time' . $tel, time());
                Redis::set('_send_msg' . $tel, $content, 60 * 3);
                return ReturnService::successReturn(200, '发送成功', $content);
            }
            return ReturnService::failedReturn(400, '发送失败');
        }
        return ReturnService::failedReturn(401, '手机号为空');
    }

    //短信登录
    public function msgLogin(Request $request)
    {
        $tel = $request->get('tel');
        $code = $request->get('code');
        //获取存储的验证码
        $old_code = Redis::get('_send_msg' . $tel);
        if (empty($tel) || empty($code)) {
            return response()->json([
                'code' => 400,
                'msg' => 'empty',
            ])->setEncodingOptions(JSON_UNESCAPED_UNICODE);
        }
        //验证码正确
        if ($code == $old_code) {
            //判断手机号是否存在 不存在则直接自动注册
            $res = UserLoginModel::where('tel', $tel)->first();
            //没有被绑定过则绑定
            if (empty($res)) {
                $res = UserLoginModel::insertGetId(['tel' => $tel]);
                $token = JwtService::getToken($res);
                //绑定并登录成功
                if ($res) {
                    return ReturnService::successReturn(200, '绑定并登录成功', $token);
                }
                //绑定失败
                return ReturnService::failedReturn(400, 'fail');
            }
            //绑定过则返回登录成功
            $token = JwtService::getToken($res);
            return ReturnService::successReturn(200, '登录成功', $token);
        }
        //验证码错误
        return ReturnService::failedReturn(400, $old_code);
    }
}
